const Koa = require("koa")
const fs = require("fs")
const path = require("path")
const compilerSfc = require("@vue/compiler-sfc")
const compilerDom = require("@vue/compiler-dom")

const app = new Koa()
//import是浏览器发起的 后端会根据node_modules去查找
//正则表达进行替换
function rewriteImport(content){
  return content.replace(/from ['|"]([^'"]+)['|"]/g,function(s0,s1){
      //console.log(s1);
      // . .. 开头的，相对路径
      if(s1[0] !== '.' && s1[1] !== "/"){
          return `from '@/modules/${s1}'`
      }else{
          s0
      }
  })
}

app.use(async ctx=>{
 ctx.body='hello vue-vite'
 const {require} = ctx
 const {url} = require;
    if(url ==="/"){
        //读取文件
        ctx.type="text/html"
        ctx.body=fs.readFileSync("./index.html","utf-8")
    }else if(url.endsWith(".js")){
        console.log("这是一个js文件")
        //针对js文件需要额外处理，不是简单的静态资源 
        const p = path.resolve(__dirname,url.slice(1));
        ctx.type="application/javascript"
        const res = fs.readFileSync(p,"utf-8")
        ctx.body= rewriteImport(res)
    }else if(url.startsWith("/@modules/")){
        //查找node_modules的东西
        const prefix = path.resolve(__dirname,'node_modules',url.replace("/@modules/",""))
        console.log(prefix);
        const module = require(prefix+'/package.json').module;
        console.log(module);
        const p = path.resolve(prefix,module);
        console.log(p);
        const res = fs.readFileSync(p,"utf-8")
        ctx.type="application/javascript";
        ctx.body= rewriteImport(res)
    }else if(url.indexOf(".vue")>-1){
        //单文件组件
        const p =  path.resolve(__dirname,url.slice(1));
        ctx.type="application/javascript";
       //ctx.body= fs.readFileSync(p,"utf-8")
        //使用vue自带的compile框架，解析单文件组件，其实相当于vue-loader所做的事情，npm install @vue/compiler-sfc(解析单文件), @vue/compiler-dom(解析模板)
       const {descriptor} = compilerSfc.parse(fs.readFileSync(p,"utf-8")); //解析含有模块的结构
        console.log(descriptor);
        ctx.body= `
        const _sript=${descriptor.script.content.replace("export default ","").replace(/\n/g,"")}`

    }
})

//监听端口
app.listen(3001,()=>{
    console.log('success listen 3001')
   
})

